<template>
  <div class="boxContent">
    <div class="appBox">
      <div class="searchList">
        <el-form :model="state.params"
                 ref="FormInstance "
                 class="boxFrom">
          <div class="searchBox">
            <template v-for="(item, index) in state.totalInputColumns"
                      :key="index">
              <el-form-item v-if="item.type == 'input'">
                <el-input clearable
                          v-model="state.params[item.key]"
                          :placeholder="item.label"></el-input>
              </el-form-item>
              <el-form-item v-if="item.type == 'select'">
                <el-select v-model="state.params[item.key]"
                           :placeholder="item.label"
                           clearable
                           v-if="item.key == 'sectorId'">
                  <el-option v-for="i in state.optionsPre"
                             :key="i"
                             :label="i.dictValue"
                             :value="i.id"></el-option>
                </el-select>

                <el-cascader v-model="state.params[item.key]"
                             :options="state.propsCity"
                             :props="state.props"
                             :placeholder="item.label"
                             clearable
                             v-if="item.key == 'cityArr'" />
              </el-form-item>
            </template>
          </div>

          <el-form-item class="btns">
            <el-button v-preventReClick
                       type="primary"
                       @click="methods.handleAction('add')"
                       v-permission="1068">创建企业</el-button>
            <el-button v-preventReClick
                       type="primary"
                       plain
                       @click="methods.handleAction('query')">搜索</el-button>
            <el-button v-preventReClick
                       @click="methods.handleAction('reset')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="tabaleBox">
        <el-table border
                  v-loading="state.loading"
                  :data="state.tableData"
                  style="width: 100%"
                  :header-cell-style="{ color: '#000' }">

          <el-table-column prop="name"
                           label="企业全称"
                           min-width="200"
                           show-overflow-tooltip
                           align="left" />
          <el-table-column prop="createAt"
                           label="注册时间"
                           show-overflow-tooltip
                           align="center"
                           width="170" />
          <el-table-column prop="childCount"
                           label="子企业(点击查看)"
                           show-overflow-tooltip
                           align="center"
                           width="135">
            <template #default="scope">
              <span class="cup primary"
                    v-if="scope.row.approveStatus == 1 && scope.row.companyType ==  1 && scope.row.childCount > 0"
                    @click="$router.push('/enterprise/son?id=' + scope.row.id + '&name=' + scope.row.name)">{{scope.row.childCount || 0}}</span>
              <span v-else>{{scope.row.childCount || 0}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="workCount"
                           label="企业就职人数"
                           show-overflow-tooltip
                           align="center"
                           width="110" />
          <el-table-column prop="recruitedCount"
                           label="已招聘人数"
                           show-overflow-tooltip
                           align="center"
                           width="110" />
          <el-table-column prop="recruitingCount"
                           label="正在招聘岗位"
                           show-overflow-tooltip
                           align="center"
                           width="110" />
          <el-table-column prop="lastDayClockCount"
                           label="昨日打卡人数"
                           show-overflow-tooltip
                           align="center"
                           width="110" />
          <el-table-column prop="balanceAmount"
                           label="企业余额"
                           show-overflow-tooltip
                           align="center"
                           width="110" />
          <el-table-column prop="usedAmount"
                           label="累计消耗金额"
                           show-overflow-tooltip
                           align="center"
                           width="110" />
          <el-table-column prop="vocationDays"
                           label="可休假天数"
                           show-overflow-tooltip
                           align="center"
                           width="110" />

          <el-table-column prop="status"
                           label="企业状态"
                           show-overflow-tooltip
                           align="center"
                           width="100">
            <template #default="scope">
              <div v-if="scope.row.status == 0"
                   class="primary">正常</div>
              <div v-if="scope.row.status == 1"
                   class="info">停用</div>
              <div v-if="scope.row.status == 2"
                   class="warning">即将欠费</div>
              <div v-if="scope.row.status == 3"
                   class="error">欠费</div>
            </template>
          </el-table-column>
          <el-table-column prop="approveStatus"
                           label="审核状态"
                           show-overflow-tooltip
                           align="center"
                           width="100">
            <template #default="scope">
              <div v-if="scope.row.approveStatus == 0"
                   class="success">
                待审核
              </div>
              <div v-if="scope.row.approveStatus == 1"
                   class="primary">
                通过
              </div>
              <div v-if="scope.row.approveStatus == 2"
                   class="error">
                未通过
              </div>
            </template>
          </el-table-column>
          <el-table-column prop=""
                           label="是否白名单"
                           show-overflow-tooltip
                           align="center"
                           width="100">
            <template #default="scope">
              <span v-if="scope.row.whiteStatus == 1"
                    class="primary">是</span>
              <span v-if="scope.row.whiteStatus == 0"
                    class="info">否</span>
            </template>
          </el-table-column>
          <el-table-column prop="managerName"
                           label="负责人"
                           show-overflow-tooltip
                           align="center"
                           width="100">
          </el-table-column>

          <el-table-column prop="btns"
                           label="操作"
                           show-overflow-tooltip
                           align="center"
                           width="300"
                           fixed="right">
            <template #default="scope">
              <div class="flex_sb btnsDatil">
                <!-- 其它操作 -->
                <!-- <div @click="methods.handleAction('', scope.row)">充值</div>
                <div @click="methods.handleAction('', scope.row)">催款</div> -->
                <div @click="methods.handleAction('edit', scope.row)"
                     v-permission="1064">编辑</div>
                <div @click="methods.handleAction('delete', scope.row)"
                     v-permission="1065"
                     class="error">
                  删除
                </div>

                <div @click="methods.handleAction('jqsz', scope.row)"
                     v-permission="1066">
                  假期设置
                </div>
                <div @click="methods.handleAction('dialog', scope.row)"
                     v-permission="1067">
                  其他操作
                </div>
                <div @click="methods.handleAction('white', scope.row)"
                     v-if="scope.row.whiteStatus == 0"
                     v-permission="1196">
                  添加白名单
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination">
        <el-pagination background
                       v-model:current-page="state.params.pageNum"
                       v-model:page-size="state.params.pageSize"
                       :page-sizes="[10, 20, 30, 50]"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="state.totalSize"
                       @size-change="methods.handleSizeChange"
                       @current-change="methods.handleCurrentChange" />
      </div>
      <el-dialog v-model="state.jqszDialog"
                 center
                 title="假期设置"
                 :width="$px2rem('400px')">
        <div class="pl20 pt10 pr20 ">
          <div>
            假期设置针对该企业员工每个自然月可休假天数，设置为当月休假天数（未要求设置每月固定为5天，设置成功后，后续月份同样为被设置的天数）
          </div>
          <div class="mt20">
            <el-input placeholder="请输入本月可休假天数"
                      v-model="state.jqszValue"
                      clearable
                      maxlength="2"
                      @input="state.jqszValue = $input.inputLimit('D10005', state.jqszValue)"></el-input>
          </div>
        </div>

        <div class="tar mt20">
          <el-button v-preventReClick
                     class="dialogClass"
                     type="primary"
                     plain
                     @click="state.jqszDialog = false">取 消</el-button>
          <el-button v-preventReClick
                     class="dialogClass"
                     type="primary"
                     @click="methods.subJqsz">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog v-model="state.dialogVisible"
                 center
                 title="其他操作"
                 :width="$px2rem('680px')"
                 top="24vh">
        <el-scrollbar :height="$px2rem('180px')">
          <div style="padding: 20px">

            <el-checkbox-group v-model="state.checkedValue"
                               :disabled="Date.now() - new Date(state.dialogData.openArrearsTime).getTime() <= 1000*60*60*24">
              <el-checkbox v-for="i in state.dialogCheckbox"
                           :key="i"
                           @change="methods.changeCheckbox(i.label,$event)"
                           :label="i.label" />
            </el-checkbox-group>
            <div class="flex mt20">
              <div class="mt4">移交负责人</div>

              <el-select class="ml12"
                         v-model="state.selectValue"
                         value-key="id"
                         clearable>
                <el-option v-for="i in state.selectList"
                           :key="i.id"
                           :label="i.userName"
                           :value="i"></el-option>
              </el-select>
            </div>
            <div class="tar mt20">

              <el-button v-preventReClick
                         class="dialogClass"
                         type="primary"
                         plain
                         @click="state.dialogVisible = false">取 消</el-button>
              <el-button v-preventReClick
                         class="dialogClass"
                         type="primary"
                         @click="methods.btnDialogSub">确 定</el-button>
            </div>
          </div>
        </el-scrollbar>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, getCurrentInstance } from "vue";
import { ElMessage, ElLoading, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
const router = useRouter();
const app = getCurrentInstance()?.proxy;
import area from "@/utils/area.js";
const initState = () => {
  return {
    jqszValue: '',
    loading: false,
    dialogCheckbox: [
      {
        label: "限制招聘发布",
        value: "1",
        type: "restrictRecruitment",
      },
      { label: "下架招聘", value: "1", type: "offlineRecruitment" },
      { label: "停止自动打卡", value: "1", type: "autoClock" },
      {
        label: "限制面试预约",
        value: "1",
        type: "interviewAppointment",
      },
      { label: "欠费开通", value: "1", type: "openArrears" },
    ],
    checkedValue: [],
    selectValue: "",
    dialogVisible: false,
    props: {
      checkStrictly: true,
      label: "value",
      value: "value",
    },
    propsCity: [],
    totalSize: 0,
    tableData: [],
    params: {
      pageNum: 1,
      descs: ["id"],
      pageSize: 10,
      sectorId: "",
      province: "",
      city: "",
      district: "",
      cityArr: [],
      shortName: "",
      keyword: "",
    },
    totalInputColumns: [
      { key: "sectorId", label: "选择行业", type: "select" },
      { key: "cityArr", label: "选择所在城市", type: "select" },
      { key: "companyName", label: "填写企业名称", type: "input" },
      { key: "managerName", label: "负责人", type: "input" },
    ],
    optionsPre: [],
    dialogData: {},
    selectList: [],
  };
};
const state = reactive(initState());
onMounted(() => {
  state.optionsPre = JSON.parse(localStorage.getItem("profession"));
  state.propsCity = area;
  methods.getDataList();
  state.propsCity = area;
});
const methods = {
  subJqsz () {
    if (state.jqszValue == '') {
      return ElMessage.error('请输入本月可休假天数')
    }
    app.$get('company/setVocation?id=' + state.dialogData.id + '&vocationdays=' + state.jqszValue).then(res => {
      if (res.code == 200) {
        ElMessage.success('设置成功')
        state.jqszValue = ''
        state.jqszDialog = false
      }
    })
  },
  // 其他操作逻辑 --- > 欠费开通和其他不能同时存在
  changeCheckbox (i, k) {
    if (i == '欠费开通' && k) {
      state.checkedValue = ['欠费开通']
    } else {
      state.checkedValue.forEach((data, index) => {
        if (data == '欠费开通') {
          state.checkedValue.splice(index, 1)
        }
      })
    }
  },
  handleAction (type, data) {
    switch (type) {
      case "query": //查询
        methods.getDataList();
        break;
      case "reset": // 重置
        state.params = initState().params;
        break;
      case "edit": // 编辑
        router.push("/enterprise/enterpriseManagement/add?id=" + data.id + '&status=' + data.approveStatus);
        break;
      case "add": // 编辑
        router.push("/enterprise/enterpriseManagement/add");
        break;
      case "white": // 白名单
        app.$post("/companyWhite/saveCompanyWhite", [data.id]).then((res) => {
          if (res.code == 200 && res.message == 'SUCCESS') {
            methods.getDataList();
            ElMessage({
              type: "success",
              message: "已添加",
            });
          }

        });
        break;
      case "jqsz": // 编辑
        state.dialogData = data;
        state.jqszDialog = true
        break;
      case "dialog": // 其他操作 查看
        state.checkedValue = []
        state.dialogData = data;
        app.$http.get("/sysuser/account/getTransferUser").then((res) => {
          state.selectList = res.data;
          res.data.forEach((r) => {
            if (r.userName == data.mname) {
              state.selectValue = r;
            }
          });
        });

        state.dialogCheckbox.forEach((res) => {
          for (let key in data) {
            if (res.type == key) {
              if (data[key] == 1) {
                state.checkedValue.push(res.label);
              }
            }
          }
        });
        state.dialogVisible = true;
        break;
      case "delete": // 删除
        ElMessageBox.confirm("请确认是否删除该企业?", "删除企业", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            app.$http.get("/company/deleteById?id=" + data.id).then((res) => {
              methods.getDataList();
              ElMessage({
                type: "success",
                message: "已删除",
              });
            });
          })
          .catch(() => {
            methods.getDataList();
            ElMessage({
              type: "info",
              message: "已取消",
            });
          });

        break;
    }
  },

  btnDialogSub () {
    const loading = ElLoading.service({
      lock: true,
      text: "加载中...",
    });
    let data = {};
    state.dialogCheckbox.forEach((label) => {
      data[label.type] = 0;
      state.checkedValue.forEach((value) => {
        if (label.label == value) {
          data[label.type] = 1;
        }
      });
    });
    data.id = state.dialogData.id;
    data.transferId = state.selectValue.id;
    data.transferName = state.selectValue.userName;
    app.$http
      .post("/company/otherOperate", data)
      .then((res) => {
        if (res.code == 200) {
          methods.getDataList();
          ElMessage({ type: "success", message: "已成功修改" });
        }
        loading.close();
        state.dialogVisible = false;
      })
      .catch((error) => {
        loading.close();
        state.dialogVisible = false;
        ElMessage({ type: "success", message: error });
      });
  },
  getDataList () {
    if (state.params.cityArr?.length) {
      state.params.province = state.params.cityArr[0];
      state.params.city = state.params.cityArr[1];
      state.params.district = state.params.cityArr[2];
    } else {
      state.params.province = "";
      state.params.city = "";
      state.params.district = "";
    }
    state.loading = true
    app.$http.post("/company/pageList", state.params).then((res) => {
      res.data.list.forEach((data) => {
        data.sectorIdData = app.$filter.sectorIdData(data.sectorId);
        data.scaleData = app.$filter.scaleData(data.scale);
      });
      state.tableData = res.data.list;
      state.totalSize = res.data.total;
      state.loading = false
    }).catch(() => {
      state.loading = false
    })
  },
  //分页变化
  handleSizeChange () {
    state.params.pageNum = 1;
    methods.getDataList();
  },
  //表格翻页
  handleCurrentChange () {
    methods.getDataList();
  },
};
</script>

<style lang="scss" scoped>
.appBox {
  background: #fff;
  border-radius: 5px;
  padding: 20px;
  height: calc(100% - 20px);
  width: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  .tabaleBox {
    overflow: hidden;
    flex: 1;
  }
  .btnsDatil {
    color: #0079fe;
    cursor: pointer;
    align-items: center;
  }
  .pagination {
    margin-top: 20px;
    height: 50px;
    display: flex;
    justify-content: flex-end;
  }
  ::v-deep(.el-dialog__body) {
    max-height: 380px;
  }
  .imgs {
    flex-wrap: wrap;
    .forbox {
      // width: 150px;
      height: 150px;
      margin: 10px 0 0 10px;
    }
    .imgBox {
      height: 100%;
      width: auto;
    }
    .videoBox {
      width: auto;
      height: 100%;
    }
  }

  // .imgs .forbox:nth-child(4n + 1) {
  //   margin-left: 0;
  // }
}
</style>
